/*
 * Created on 2005-1-10
 *
 */
package com.taobao.common.dao.persistence;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.commons.logging.LogFactory;

/**
 * @author xingdian
 * @version $Id: DBRouteRule.java,v 1.1 2005/05/13 08:11:21 xingdian Exp $
 */
public class DBRouteRule {
  private String  dbName;
  private String  ruleBaseName;
  private String  rule;
  private Pattern pattern;

  /**
   * ��ʼ��
   */
  public DBRouteRule(String dbName, String ruleBaseName, String rule) {
    this.dbName = dbName;
    this.ruleBaseName = ruleBaseName;
    this.rule = rule;
    init();
  }

  /**
   * ����һ������
   *
   * @param ruleBaseName
   *          ��ݿ�ڵ�����
   * @param rule
   *          ����,һ��������ʽ
   */
  public void addRule(String ruleBaseName, String rule) {
    try {
      this.ruleBaseName = ruleBaseName;
      this.rule = rule;
      pattern = Pattern.compile(rule);
    } catch (PatternSyntaxException e) {
      LogFactory.getLog("Persistence").debug("Persistence routing rule " + rule + " is inavailble to compile." + e, e);
    }
  }

  /**
   * �Ƿ���ָ����������ʽƥ��
   *
   * @param ruleBaseName
   *
   * @return
   */
  public boolean isMatched(String ruleBaseName) {
    if ((ruleBaseName == null) || (ruleBaseName.length() <= 0)) {
      return false;
    }

    CharSequence cs = ruleBaseName.subSequence(0, ruleBaseName.length() - 1);
    Matcher m = pattern.matcher(cs);

    return m.matches();
  }

  /**
   * ������ݿ�ڵ�����
   *
   * @return
   */
  public String getdbName() {
    return dbName;
  }

  /**
   * @return Returns the pattern.
   */
  public Pattern getPattern() {
    return pattern;
  }

  /**
   * ���ظù���Ĺ������
   *
   * @return Returns
   */
  public String getRuleBaseName() {
    return ruleBaseName;
  }

  /**
   * ���ظù���
   *
   * @return Returns
   */
  public String getRule() {
    return rule;
  }

  private void init() {
    try {
      pattern = Pattern.compile(rule);
    } catch (PatternSyntaxException e) {
      LogFactory.getLog("DBRouteRule").debug("DBRouteRule routing rule " + rule + " is inavailble to compile." + e, e);
    }
  }
}
